package cn.itcast.controller;

import cn.itcast.constant.MessageConstant;
import cn.itcast.entity.Result;
import cn.itcast.service.ReportService;
import cn.itcast.service.SetmealService;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.dubbo.config.annotation.Reference;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 报表操作
 */
@RestController
@RequestMapping("/report")
public class ReportController {

    @Reference
    private SetmealService setmealService;

    @Reference
    private ReportService reportService;


    /**
     * 套餐预定统计(餅形圖)
     *
     * @return
     */
    @RequestMapping("/setmeals")
    public Result findReportSetmeal () {
        //构建一个map集合,封装响应数据
        Map<String, Object> data = new HashMap<>();
        try {
            List<Map<String, Object>> setmealCount = this.setmealService.findSetmealOrderedCount();
            data.put("setmealCount", setmealCount);
            //遍历集合,取出map的名称
            List<String> setmealNames = new ArrayList<>();
            for (Map<String, Object> map : setmealCount) {
                String name = (String) map.get("nama");
                setmealNames.add(name);//套餐的名称
            }
            data.put("setmealNames", setmealNames);

            return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS, data);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
        }
    }

    /**
     * 会员数量统计
     *
     * @return
     */
    @RequestMapping("/member/count")
    public Result membercount () {
        Map<String, Object> map = new HashMap<>();
        List<String> months = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, -12);
        for (int i = 0; i < 12; i++) {
            calendar.add(Calendar.MONTH, 1);//当前时间后推一个月
            Date date = calendar.getTime();
            months.add(new SimpleDateFormat("yyyy.MM").format(date));
        }
        map.put("months", months);
        List<Integer> memberCount = this.reportService.findMemberByMonths(months);
        map.put("memberCount", memberCount);
        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
    }

    /**
     * 运用数据统计
     *
     * @return
     */
    @RequestMapping("/business")
    public Result business () {

        try {
            Map<String, Object> data = this.reportService.findBusiness();

            return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS, data);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    /**
     * 导出运营数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/export/business")
    public Result exportbusiness ( HttpServletResponse response ) {
        try {
            Map<String, Object> data = this.reportService.findBusiness();
            String reportDate = (String) data.get("reportDate");
            Integer todayNewMember = (Integer) data.get("todayNewMember");
            Integer totalMember = (Integer) data.get("totalMember");
            Integer thisWeekNewMember = (Integer) data.get("thisWeekNewMember");
            Integer thisMonthNewMember = (Integer) data.get("thisMonthNewMember");
            Integer todayOrderNumber = (Integer) data.get("todayOrderNumber");
            Integer todayVisitsNumber = (Integer) data.get("todayVisitsNumber");
            Integer thisWeekOrderNumber = (Integer) data.get("thisWeekOrderNumber");
            Integer thisWeekVisitsNumber = (Integer) data.get("thisWeekVisitsNumber");
            Integer thisMonthOrderNumber = (Integer) data.get("thisMonthOrderNumber");
            Integer thisMonthVisitsNumber = (Integer) data.get("thisMonthVisitsNumber");
            List<Map> list = (List<Map>) data.get("hotSetmeal");

            String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
            String file =path+"static/template/report_template.xlsx";
            //创建表格对象
            XSSFWorkbook xk = new XSSFWorkbook(new FileInputStream(new File(file)));
            //读取第一个工作表
            XSSFSheet sheetAt = xk.getSheetAt(0);
            XSSFRow row = sheetAt.getRow(2);
            XSSFCell cell = row.getCell(5);
            cell.setCellValue(reportDate);//报表日期

            row = sheetAt.getRow(4);
            row.getCell(5).setCellValue(todayNewMember);//本日新增会员数
            row.getCell(7).setCellValue(totalMember);//总会员数

            row = sheetAt.getRow(5);
            row.getCell(5).setCellValue(thisWeekNewMember);//本周新增会员数
            row.getCell(7).setCellValue(thisMonthNewMember);//本月新增会员数

            row = sheetAt.getRow(7);
            row.getCell(5).setCellValue(todayOrderNumber);//本日预约数
            row.getCell(7).setCellValue(todayVisitsNumber);//本日到诊数

            row = sheetAt.getRow(8);
            row.getCell(5).setCellValue(thisWeekOrderNumber);//本周预约数
            row.getCell(7).setCellValue(thisWeekVisitsNumber);//本周到诊数

            row = sheetAt.getRow(9);
            row.getCell(5).setCellValue(thisMonthOrderNumber);//本月预约数
            row.getCell(7).setCellValue(thisMonthVisitsNumber);//本月到诊数

            int Num = 12;
            for (Map map : list) {
                String name = (String) map.get("name");
                Long setmeal_count = (Long) map.get("setmeal_count");
                BigDecimal proportion = (BigDecimal) map.get("proportion");
                row = sheetAt.getRow(Num++);
                row.getCell(4).setCellValue(name);//套餐数
                row.getCell(5).setCellValue(setmeal_count);//预约数
                row.getCell(6).setCellValue(proportion.doubleValue());//占比例
            }
            //通过输出流进行表下载
            OutputStream out = response.getOutputStream();
            //设置响应信息
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");
            xk.write(out);

            out.flush();
            out.close();
            xk.close();

            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }


    }

    /**
     * 收入统计
     */

    @GetMapping("/income")
    public Result findIncome(){

        //计算过去一年的12个月
        Map<String,Object> map=new HashMap<>();//构建map集合封装响应数据
        Calendar calendar=Calendar.getInstance();//获取当前时间
        List<String> months=new ArrayList<>();
        calendar.add(Calendar.MONTH,-12);//获取12月之前的时间

        for (int i = 0; i < 12; i++) {
            calendar.add(Calendar.MONTH,1);//当前月向后推一个月
            Date time = calendar.getTime();
            months.add(new SimpleDateFormat("yyyy-MM").format(time));
        }
        map.put("months",months);


        List<Double> incomeCount=this.reportService.findIncome(months);
        map.put("incomeCount",incomeCount);


        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,map);

    }

    /**
     * 预约/支付统计
     */

    @GetMapping("/orderPay")
    public Result findOrder(){

        //计算过去一年的12个月
        Map<String,Object> map=new HashMap<>();//构建map集合封装响应数据
        Calendar calendar=Calendar.getInstance();//获取当前时间
        List<String> months=new ArrayList<>();
        calendar.add(Calendar.MONTH,-12);//获取12月之前的时间

        for (int i = 0; i < 12; i++) {
            calendar.add(Calendar.MONTH,1);//当前月向后推一个月
            Date time = calendar.getTime();
            months.add(new SimpleDateFormat("yyyy-MM").format(time));
        }
        map.put("months",months);

        //查询每月预约数量
        List<Integer> orderCount=this.reportService.findOrder(months);
        map.put("orderCount",orderCount);
        //调用收入统计的方法
        List<Double> payCount=this.reportService.findIncome(months);
        map.put("payCount",payCount);


        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,map);

    }


}




